package co.yixiang.modules.shop.rest;

import co.yixiang.aop.log.Log;
import co.yixiang.modules.shop.domain.YxGoods;
import co.yixiang.modules.shop.domainExcel.YxGoodsExcelData;
import co.yixiang.modules.shop.service.YxGoodsService;
import co.yixiang.modules.shop.service.dto.YxGoodsDto;
import co.yixiang.modules.shop.service.dto.YxGoodsQueryCriteria;
import co.yixiang.modules.shop.utils.IOUtil;
import co.yixiang.utils.OrderUtil;
import co.yixiang.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author frq
 * @date 2020-08-24
 */
@Slf4j
@Api(tags = "测试商品表管理")
@RestController
@RequestMapping("/api/yxGoods")
public class YxGoodsController {
    @Autowired
    private YxGoodsService yxGoodsService;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

    @Log("easyExcel导入数据")
    @PostMapping("/doEasyExcelImportGoods")
    public ResponseEntity doEasyExcelImportGoods(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("easyExcel导入数据开始时间:" + simpleDateFormat.format(new Date()));
        yxGoodsService.doEasyExcelImportGoods(file.getInputStream());
        log.info("easyExcel导入数据结束时间:" + simpleDateFormat.format(new Date()));
        return new ResponseEntity("成功", HttpStatus.OK);
    }

    @Log("POI导入数据")
    @PostMapping("/doPOIImportGoods")
    public ResponseEntity doPOIImportGoods(@RequestParam("file") MultipartFile file) {
        log.info("POI导入数据开始时间:" + simpleDateFormat.format(new Date()));
        List<List<String>> list = new ArrayList<List<String>>();
        //收集导入失败商品集合(用于导出)
        String filaName = file.getOriginalFilename();// 获取文件名
        String prefix = filaName.substring(filaName.lastIndexOf(".") + 1);// 获取文件后缀
        try {
            InputStream in = file.getInputStream();
            if ("xlsx".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsxByType(in);// 导入xlsx格式
            } else if ("xls".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsByType(in);// 导入xls格式
            }
            yxGoodsService.doPOIImportGoods(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("POI导入数据结束时间:" + simpleDateFormat.format(new Date()));
        return new ResponseEntity("成功", HttpStatus.OK);
    }

    @Log("easyExcel导出数据")
    @GetMapping(value = "/easyExceldownload")
    public void easyExceldownload(HttpServletResponse response, YxGoodsQueryCriteria criteria) throws IOException {
        log.info("导出数据开始时间:" + simpleDateFormat.format(new Date()));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            List<YxGoodsExcelData> list = yxGoodsService.findListYxGoods();
            com.alibaba.excel.EasyExcel.write(response.getOutputStream(), YxGoodsExcelData.class).autoCloseStream(Boolean.FALSE).sheet("商品信息")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
        log.info("导出数据结束时间:" + simpleDateFormat.format(new Date()));
    }

    @Log("POI导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/downloadPOI")
    @PreAuthorize("@el.check('yxGoods:list')")
    public void downloadPOI(HttpServletResponse response, YxGoodsQueryCriteria criteria) throws IOException {
        log.info("导出数据开始时间:" + simpleDateFormat.format(new Date()));
        List<YxGoodsDto> list = yxGoodsService.queryAll(criteria);
        yxGoodsService.download(list, response);
        log.info("导出数据结束时间:" + simpleDateFormat.format(new Date()));
    }


    @GetMapping
    @Log("查询测试商品表")
    @ApiOperation("查询测试商品表")
    @PreAuthorize("@el.check('yxGoods:list')")
    public ResponseEntity<Object> getYxGoodss(YxGoodsQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(yxGoodsService.queryAll(criteria, pageable), HttpStatus.OK);
    }


}